package com.fulizhe.catlocal.integration.springboot.metric;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.message.Message;

import cn.hutool.core.convert.Convert;

public class CatMetricFilter implements Filter {

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
			throws IOException, ServletException {
		final HttpServletResponse response = Convert.convert(HttpServletResponse.class, resp);

		final HttpServletRequest request = Convert.convert(HttpServletRequest.class, req);
		final CacheHttpServletRequestWrapper bladeRequest = new CacheHttpServletRequestWrapper(request);
		final CacheHttpResponseWrapper response2 = new CacheHttpResponseWrapper(response);

		filterChain.doFilter(bladeRequest, response2);

		// 入參
		final Object requestParams = getRequestParams(request);
		Cat.logEvent(CatConstants.TYPE_URL, CatConstants.TYPE_URL + ".param", Message.SUCCESS,
				requestParams.toString());

		// 出參
		byte[] bytes = response2.getBytes();
		Cat.logEvent(CatConstants.TYPE_URL, CatConstants.TYPE_URL + ".result", Message.SUCCESS, new String(bytes));

		response2.setContentLength(-1);
		ServletOutputStream out = response.getOutputStream();
		out.write(bytes);
		out.flush();
	}

	private Object getRequestParams(final HttpServletRequest request) {
		return WebUtil.getRequestContent(request);
	}

}
